package com.chb.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chb.app.mapper.*;
import com.chb.app.service.BackService;
import com.chb.app.utils.HttpClient;
import com.chb.app.vo.PayDto;
import com.github.wxpay.sdk.WXPayUtil;
import com.hos.entity.his.*;
import com.hos.utils.IdGeneratorUtil;
import com.hos.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author: 陈海彬
 * @date: Created in 2023/12/29 10:56
 * @description:
 * @modified By:
 * @version:
 */
@Service
@Slf4j
public class BackServiceImpl implements BackService {

    @Value("${weixin.appid}")
    private String appId;

    @Value("${weixin.mch_id}")
    private String mchId;

    @Value("${weixin.api_key}")
    private String apiKey;

    @Resource
    private OrderBackfeeMapper orderBackfeeMapper;
    @Resource
    private OrderBackfeeItemMapper orderBackfeeItemMapper;
    @Resource
    private CareOrderMapper careOrderMapper;
    @Resource
    private CareOrderItemMapper careOrderItemMapper;
    @Resource
    private OrderChargeMapper orderChargeMapper;
    @Resource
    private OrderChargeItemMapper orderChargeItemMapper;


    @Override
    public Result<String> back(String chId) {
        // 1.查询订单列表 状态为已完成
        List<CareOrderItem> careOrderList = this.selectCareOrder(chId);
        // 2.修改收费列表并拿到收费id
        OrderCharge orderCharge = this.updateOrderChargeItem(chId);
        // 4.查询收费子项
        List<OrderChargeItem> chargeItemList = this.selectOrderCharge(chId);
        // 3.进行添加相应的退费记录
        OrderBackfee orderBackfee = this.insertBack(orderCharge, chargeItemList);

        // 5.进行微信退费
        String backWxPay = this.backWxPay(orderBackfee);
        return new Result<>(200, "退费成功", backWxPay);
    }

    private List<OrderChargeItem> selectOrderCharge(String chId) {
        LambdaQueryWrapper<OrderCharge> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderCharge::getChId, chId);
        OrderCharge orderCharge = this.orderChargeMapper.selectOne(wrapper);
        LambdaQueryWrapper<OrderChargeItem> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(OrderChargeItem::getOrderId, orderCharge.getOrderId());
        return this.orderChargeItemMapper.selectList(wrapper1);
    }

    private OrderBackfee insertBack(OrderCharge orderCharge, List<OrderChargeItem> careOrderList) {
        OrderBackfee orderBackfee = new OrderBackfee();
        String backId = IdGeneratorUtil.nextId("ODB");
        orderBackfee.setBackId(IdGeneratorUtil.nextId(backId));  // 设置退费id
        orderBackfee.setBackAmount(orderCharge.getOrderAmount()); // 设置总费用
        orderBackfee.setChId(orderCharge.getChId());  // 设置病例id
        orderBackfee.setRegId(orderCharge.getRegId());  // 设置挂号单
        orderBackfee.setPatientName(orderCharge.getPatientName());
        orderBackfee.setBackStatus("1");   // 设置退费状态  1 退费成功
        String payType = orderCharge.getPayType();
        orderBackfee.setBackType(payType);  // 设置退费类型
        orderBackfee.setOrderId(orderCharge.getOrderId());  // 关联订单id
        orderBackfee.setBackPlatformId(orderCharge.getPayPlatformId());  // 交易id
        orderBackfee.setCreateTime(new Date());
        orderBackfee.setCreateBy("超级管理员");
        // 进行插入语句
        this.orderBackfeeMapper.insert(orderBackfee);

        // 插入响应的子项
        for (OrderChargeItem careOrderItem : careOrderList) {
            OrderBackfeeItem orderBackfeeItem = new OrderBackfeeItem();
            orderBackfeeItem.setItemId(careOrderItem.getItemId());
            orderBackfeeItem.setCoId(careOrderItem.getCoId());
            orderBackfeeItem.setItemName(careOrderItem.getItemName());
            orderBackfeeItem.setItemPrice(careOrderItem.getItemPrice());
            orderBackfeeItem.setItemNum(careOrderItem.getItemNum().intValue());
            orderBackfeeItem.setItemAmount(careOrderItem.getItemAmount().intValue());
            orderBackfeeItem.setBackId(careOrderItem.getOrderId());
            orderBackfeeItem.setItemType(careOrderItem.getItemType());
            orderBackfeeItem.setStatus("2");
            this.orderBackfeeItemMapper.insert(orderBackfeeItem);
        }
        return orderBackfee;
    }

    private String backWxPay(OrderBackfee orderBackfee) {
        // TODO 此处微信支付退款需要 双向证书
        // 设置请求的参数————格式为xml格式
        Map<String, String> params = new HashMap<>();
        params.put("appid", appId);   // 公众号
        params.put("mch_id", mchId);  // 商户号
        params.put("nonce_str", WXPayUtil.generateNonceStr());      // 32位随机字符串
        params.put("out_trade_no", orderBackfee.getChId());                        // 商户订单号
        params.put("out_refund_no", orderBackfee.getBackId());  // 商户系统内部的退款单号
        // params.put("total_fee", new BigDecimal(order.getTotalFee().multiply(new BigDecimal(100)).longValue()) + "");
        params.put("total_fee", "1");  // 设置金额
        params.put("refund_fee", "1");  // s设置退款金额
        params.put("spbill_create_ip", "127.0.0.1");    // 未来写成项目部署的ip
        params.put("notify_url", "http://localhost:9000/pay/back");  // 回调地址
        params.put("trade_type", "NATIVE");                          // 交易类型

        try {
            // 2.创建HttpClient对象 作为远程调用
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            // 支持http协议
            client.setHttps(true);
            client.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
            // 发送请求
            client.post();

            // 获得响应对象
            String content = client.getContent();

            Map<String, String> map = WXPayUtil.xmlToMap(content);
            // log.error("退款结果：" + map.get("result_code"));

            if ("SUCCESS".equals(map.get("result_code"))) {
                String codeUrl = map.get("code_url");
                return "退款成功";
                // return new PayDto(codeUrl, price, chId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // return new PayDto();
        return "";
    }

    private OrderCharge updateOrderChargeItem(String chId) {
        LambdaQueryWrapper<OrderCharge> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderCharge::getChId, chId);
        OrderCharge orderCharge = this.orderChargeMapper.selectOne(wrapper);
        // 进行修改收费id
        LambdaUpdateWrapper<OrderChargeItem> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(OrderChargeItem::getOrderId, orderCharge.getOrderId())
                .set(OrderChargeItem::getStatus, "2");
        return orderCharge;
    }


    /**
     * @param chId
     * @return java.util.List<com.hos.entity.his.CareOrder>
     * @create by: 陈海彬
     * @description: 根据病例id查询订单
     * @create time: 2023/12/29 11:06
     */
    private List<CareOrderItem> selectCareOrder(String chId) {
        LambdaQueryWrapper<CareOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CareOrder::getChId, chId);
        List<CareOrder> careOrderList = this.careOrderMapper.selectList(wrapper);
        List<CareOrderItem> careOrderItemList = new ArrayList<>();
        for (CareOrder careOrder : careOrderList) {
            LambdaUpdateWrapper<CareOrderItem> wrapper1 = new LambdaUpdateWrapper<>();
            wrapper1.eq(CareOrderItem::getCoId, careOrder.getCoId())
                    .set(CareOrderItem::getStatus, "2");
            this.careOrderItemMapper.update(wrapper1);
            List<CareOrderItem> orderItems = this.careOrderItemMapper.selectList(wrapper1);
            careOrderItemList.addAll(orderItems);
        }
        return careOrderItemList;
    }
}